import { Vec3 } from '@/core/types';
import { BlockType } from '@/blocks/types';
import { WorldManager } from '@/world/WorldManager';
import { RedstoneSystem } from './RedstoneSystem';
import { RedstoneMechanics } from './RedstoneMechanics';

export class RedstoneManager {
  private redstoneSystem: RedstoneSystem;
  private redstoneMechanics: RedstoneMechanics;
  private worldManager: WorldManager;
  private visualEffects: Map<string, any> = new Map();

  constructor(worldManager: WorldManager) {
    this.worldManager = worldManager;
    this.redstoneSystem = new RedstoneSystem(worldManager);
    this.redstoneMechanics = new RedstoneMechanics(worldManager);
  }

  public update(deltaTime: number): void {
    this.redstoneSystem.update(deltaTime);
    this.redstoneMechanics.update(deltaTime);
    this.updateVisualEffects(deltaTime);
  }

  public onBlockPlaced(position: Vec3, blockType: BlockType): void {
    if (this.isRedstoneBlock(blockType)) {
      this.redstoneSystem.addRedstoneComponent(position, blockType);
      this.createVisualEffect(position, blockType);
    } else if (this.isMechanicalDevice(blockType)) {
      this.redstoneMechanics.addDevice(position, this.getDeviceType(blockType));
    }
  }

  public onBlockBroken(position: Vec3, blockType: BlockType): void {
    if (this.isRedstoneBlock(blockType)) {
      this.redstoneSystem.removeRedstoneComponent(position);
      this.removeVisualEffect(position);
    } else if (this.isMechanicalDevice(blockType)) {
      this.redstoneMechanics.removeDevice(position);
    }
  }

  public onBlockInteracted(position: Vec3, blockType: BlockType): boolean {
    // 处理可交互的红石组件（按钮、拉杆等）
    switch (blockType) {
      case BlockType.REDSTONE_TORCH:
        return this.toggleRedstoneTorch(position);
      default:
        return false;
    }
  }

  private toggleRedstoneTorch(position: Vec3): boolean {
    const currentPower = this.redstoneSystem.getPowerLevel(position);
    const newPower = currentPower > 0 ? 0 : 15;
    
    this.redstoneSystem.setPowerSource(position, newPower);
    this.updateVisualEffect(position, BlockType.REDSTONE_TORCH, newPower > 0);
    
    console.log(`Redstone torch at (${position.x}, ${position.y}, ${position.z}) ${newPower > 0 ? 'activated' : 'deactivated'}`);
    return true;
  }

  private createVisualEffect(position: Vec3, blockType: BlockType): void {
    const key = this.getPositionKey(position);
    
    // 创建红石粒子效果或发光效果
    const effect = {
      position: { ...position },
      type: blockType,
      isActive: this.redstoneSystem.isPowered(position),
      lastUpdate: Date.now(),
      particles: []
    };

    this.visualEffects.set(key, effect);
  }

  private updateVisualEffect(position: Vec3, blockType: BlockType, isActive: boolean): void {
    const key = this.getPositionKey(position);
    const effect = this.visualEffects.get(key);
    
    if (effect) {
      effect.isActive = isActive;
      effect.lastUpdate = Date.now();
    }
  }

  private removeVisualEffect(position: Vec3): void {
    const key = this.getPositionKey(position);
    this.visualEffects.delete(key);
  }

  private updateVisualEffects(deltaTime: number): void {
    for (const [key, effect] of this.visualEffects) {
      const currentPower = this.redstoneSystem.getPowerLevel(effect.position);
      const shouldBeActive = currentPower > 0;
      
      if (effect.isActive !== shouldBeActive) {
        effect.isActive = shouldBeActive;
        this.onVisualEffectChanged(effect);
      }
    }
    
    // 更新机械装置状态
    this.updateMechanicalDevices();
  }

  private updateMechanicalDevices(): void {
    // 检查所有机械装置周围的红石信号
    // 这里简化为检查熔炉周围的红石信号
    // 在实际实现中会遍历所有已注册的机械装置
  }

  private onVisualEffectChanged(effect: any): void {
    // 这里可以添加视觉效果的更新逻辑
    // 比如改变红石线的颜色、添加粒子效果等
    const powerLevel = this.redstoneSystem.getPowerLevel(effect.position);
    
    if (effect.type === BlockType.REDSTONE_WIRE) {
      // 红石线根据功率等级改变颜色
      const intensity = powerLevel / 15;
      console.log(`Redstone wire at (${effect.position.x}, ${effect.position.y}, ${effect.position.z}) power: ${powerLevel}, intensity: ${intensity.toFixed(2)}`);
    } else if (effect.type === BlockType.REDSTONE_TORCH) {
      // 红石火把的开关状态
      console.log(`Redstone torch at (${effect.position.x}, ${effect.position.y}, ${effect.position.z}) ${effect.isActive ? 'ON' : 'OFF'}`);
    }
  }

  private isRedstoneBlock(blockType: BlockType): boolean {
    return blockType === BlockType.REDSTONE_WIRE || 
           blockType === BlockType.REDSTONE_TORCH;
  }

  private isMechanicalDevice(blockType: BlockType): boolean {
    // 这里可以扩展更多机械装置类型
    return blockType === BlockType.FURNACE; // 简化：用熔炉代表活塞
  }

  private getDeviceType(blockType: BlockType): string {
    switch (blockType) {
      case BlockType.FURNACE:
        return 'piston'; // 简化：用熔炉代表活塞
      default:
        return 'unknown';
    }
  }

  private getPositionKey(position: Vec3): string {
    return `${Math.floor(position.x)},${Math.floor(position.y)},${Math.floor(position.z)}`;
  }

  // 公共查询方法
  public isPowered(position: Vec3): boolean {
    return this.redstoneSystem.isPowered(position);
  }

  public getPowerLevel(position: Vec3): number {
    return this.redstoneSystem.getPowerLevel(position);
  }

  public getDebugInfo(): any {
    return {
      redstoneSystem: this.redstoneSystem.getDebugInfo(),
      visualEffects: this.visualEffects.size
    };
  }

  // 清理方法
  public clear(): void {
    this.redstoneSystem.clear();
    this.visualEffects.clear();
  }
}